# api/auth.py
"""
Author: didiplus
Description: 认证相关API
Date: 2025-08-20 21:00:00
LastEditors: didiplus
LastEditTime: 2025-08-20 21:00:00
FilePath: /WeChatBot/app/api/auth.py
Version: 1.0
"""
from fastapi import APIRouter, Depends, HTTPException, status,Form,Header
from sqlalchemy.orm import Session
from datetime import datetime, timedelta

from typing import Optional
from schemas import TokenVerifyResponse

# 使用相对导入方式引入模块
from core import get_db
from core.settings import settings
from schemas.user import UserCreate, UserLogin, Token
from services.user import UserService
from utils import create_access_token,verify_token

router = APIRouter()



@router.post("/register", response_model=Token, status_code=status.HTTP_201_CREATED)
def register_user(user_create: UserCreate, db: Session = Depends(get_db)):
    """
    用户注册
    """
    user_service = UserService(db)
    
    try:
        user = user_service.create_user(user_create=user_create)
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    
    # 创建访问令牌
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"user_id": user.id}, expires_delta=access_token_expires
    )
    
    return {"access_token": access_token, "token_type": "bearer"}




@router.post("/login", response_model=Token)
def login_user(user_login: UserLogin, db: Session = Depends(get_db)):
    """
    用户登录
    """
    user_service = UserService(db)
    user = user_service.authenticate_user(
        username=user_login.username, 
        password=user_login.password
    )
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 创建访问令牌
    access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"user_id": user.id, "username": user_login.username}, 
        expires_delta=access_token_expires
    )
    
    return {"access_token": access_token, "token_type": "bearer"}







@router.post("/verify-token", response_model=TokenVerifyResponse)
def verify_token_endpoint(authorization: Optional[str] = Header(None)):
    """
    验证token是否有效
    从Authorization header中获取token
    """
    if not authorization:
        return TokenVerifyResponse(valid=False)
    try:
        token_data = verify_token(authorization)
        return TokenVerifyResponse(
            valid=True,
            user_id=token_data.user_id,
            # username=token_data.username
        )
    except HTTPException:
        return TokenVerifyResponse(valid=False)
    except Exception as e:
        return TokenVerifyResponse(valid=False)